from rest_framework import serializers
from .models import Comment
from apps.articles.models import Like


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    commentId = serializers.IntegerField(source='comment_id')
    pCommentId = serializers.IntegerField(source='p_comment_id')
    articleId = serializers.IntegerField(source='article.article_id')
    imgPath = serializers.CharField(source='img_path')
    userId = serializers.IntegerField(source='user.user_id')
    nickName = serializers.CharField(source='nick_name')
    avatar = serializers.CharField(source='user.avatar')
    replyUserId = serializers.IntegerField(source='reply_user_id')
    replyNickName = serializers.CharField(source='reply_nick_name')
    topType = serializers.IntegerField(source='top_type')
    postTime = serializers.DateTimeField(source='post_time', format='%Y-%m-%d %H:%M:%S')
    goodCount = serializers.IntegerField(source='good_count')
    likeType = serializers.SerializerMethodField()
    children = serializers.SerializerMethodField()
    
    class Meta:
        model = Comment
        fields = [
            'commentId', 'pCommentId', 'articleId', 'content', 'imgPath',
            'userId', 'nickName', 'avatar', 'replyUserId', 'replyNickName', 'topType',
            'postTime', 'goodCount', 'likeType', 'children'
        ]
        
    def get_likeType(self, obj):
        """获取当前用户对评论的点赞状态"""
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            if Like.objects.filter(like_type=1, object_id=obj.comment_id, user=request.user).exists():
                return 1
        return 0
        
    def get_children(self, obj):
        """获取子评论"""
        if obj.p_comment_id == 0:  # 只有顶级评论才获取子评论
            children = Comment.objects.filter(p_comment_id=obj.comment_id).order_by('post_time')
            return CommentSerializer(children, many=True, context=self.context).data
        return []


class CommentCreateSerializer(serializers.ModelSerializer):
    """评论创建序列化器"""
    userId = serializers.IntegerField(source='user_id', write_only=True)
    articleId = serializers.IntegerField(source='article_id', write_only=True)
    pCommentId = serializers.IntegerField(source='p_comment_id', write_only=True)
    image = serializers.CharField(source='img_path', write_only=True, required=False, allow_blank=True)
    replyUserId = serializers.IntegerField(source='reply_user_id', write_only=True, required=False)
    
    class Meta:
        model = Comment
        fields = ['userId', 'articleId', 'pCommentId', 'content', 'image', 'replyUserId']
        
    def validate(self, attrs):
        content = attrs.get('content', '').strip()
        img_path = attrs.get('img_path', '').strip()
        
        if not content and not img_path:
            raise serializers.ValidationError("The comment content and image must have at least one")
        
        return attrs
        
    def create(self, validated_data):
        user_id = validated_data.pop('user_id')
        article_id = validated_data.pop('article_id')
        p_comment_id = validated_data.get('p_comment_id', 0)
        reply_user_id = validated_data.pop('reply_user_id', None)
        
        # 获取相关对象
        from apps.users.models import User
        from apps.articles.models import Article
        
        user = User.objects.get(user_id=user_id)
        article = Article.objects.get(article_id=article_id)
        
        # 如果是回复评论（p_comment_id > 0），自动设置 reply_user_id
        if p_comment_id and p_comment_id > 0:
            try:
                parent_comment = Comment.objects.get(comment_id=p_comment_id)
                # 设置被回复用户的ID
                reply_user_id = parent_comment.user.user_id
            except Comment.DoesNotExist:
                # 如果父评论不存在，保持原有的 reply_user_id
                pass
        
        # 创建评论
        comment = Comment.objects.create(
            user=user,
            article=article,
            reply_user_id=reply_user_id,
            **validated_data
        )
        
        # 更新文章评论数
        article.comment_count += 1
        article.save()
        
        return comment